package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.util.LogincException;
import cn.wolfcode.rbac.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import java.util.List;

/**
 * @Description TODO
 * @ClassName EmployeeServiceImpl
 * @Author luhui
 * @date 2020.06.13 12:52
 * @version: 1.0
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteEmpAndRoleRelation(id,null);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Employee employee,Long[] ids) {
        if (employee.getId() == null) {
            employeeMapper.insert(employee);
        } else {
            employeeMapper.updateByPrimaryKey(employee);
            employeeMapper.deleteEmpAndRoleRelation(employee.getId(),null);
        }
        if (ids != null) {
            for (Long id : ids) {
                employeeMapper.insertEmpAndRoleRelation(employee.getId(), id);
            }
        }
    }

    @Override
    public PageResult query(QueryObject queryObject) {
        int count = employeeMapper.selectForCount(queryObject);
        if (count == 0){
            return PageResult.DEFAULT_PAGE;
        }

        List<Employee> list = employeeMapper.selectForList(queryObject);
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),list,count);
    }

    @Override
    public void login(String name, String password) {
        Employee currentEmp = employeeMapper.selectByNameAndPassword(name,password);
        if (currentEmp == null){
            throw new LogincException("亲，您输入的账号或密码错误！请重新输入！");
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        requestAttributes.getRequest().getSession().setAttribute("EMPLOYEE_IN_SESSION",currentEmp);
        List<String> expressions = permissionMapper.selectExpressionByEmpId(currentEmp.getId());
        requestAttributes.getRequest().getSession().setAttribute("EXPRESSION_IN_SESSION",expressions);
    }
}